home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5448 < prev    next >
Encoding:
Text File  |  1996-08-05  |  34.2 KB  |  841 lines

  1. Path: news.wyoming.com!usenet
  2. From: dcromley@wyoming.com (RePost)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ:  re-posting #4/4
  5. Date: 5 Feb 1996 00:06:53 GMT
  6. Organization: wyoming.com LLC
  7. Message-ID: <4f3hmt$a96@horn.wyoming.com>
  8. NNTP-Posting-Host: cys-cap-6.wyoming.com
  9. Mime-Version: 1.0
  10. X-Newsreader: WinVN 0.99.2
  11.  
  12. (reposted from M. Cline to get them together)
  13. Summary: Please read this before posting to comp.lang.c++
  14.  
  15. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  16. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  17. Posting 4 of 4.
  18. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  19.  
  20. ==============================================================================
  21. SECTION 17: Linkage-to/relationship-with C
  22. ==============================================================================
  23.  
  24. Q105: How can I call a C function "f(int,char,float)" from C++ code?
  25.  
  26. Tell the C++ compiler that it is a C function:
  27.         extern "C" void f(int,char,float);
  28.  
  29. Be sure to include the full function prototype.  A block of many C functions
  30. can be grouped via braces, as in:
  31.  
  32.         extern "C" {
  33.           void* malloc(size_t);
  34.           char* strcpy(char* dest, const char* src);
  35.           int   printf(const char* fmt, ...);
  36.         }
  37.  
  38. ==============================================================================
  39.  
  40. Q106: How can I create a C++ function "f(int,char,float)" that is callable by
  41.    my C code?
  42.  
  43. The C++ compiler must know that "f(int,char,float)" is to be called by a C
  44. compiler using the same "extern C" construct detailed in the previous FAQ.
  45. Then you define the function in your C++ module:
  46.  
  47.         void f(int x, char y, float z)
  48.         {
  49.           //...
  50.         }
  51.  
  52. The "extern C" line tells the compiler that the external information sent to
  53. the linker should use C calling conventions and name mangling (e.g., preceded
  54. by a single underscore).  Since name overloading isn't supported by C, you
  55. can't make several overloaded fns simultaneously callable by a C program.
  56.  
  57. Caveats and implementation dependencies:
  58.  * your "main()" should be compiled with your C++ compiler (for static init).
  59.  * your C++ compiler should direct the linking process (for special libraries).
  60.  * your C and C++ compilers may need to come from same vendor and have
  61.    compatible versions (i.e., needs same calling convention, etc.).
  62.  
  63. ==============================================================================
  64.  
  65. Q107: Why's the linker giving errors for C/C++ fns being called from C++/C
  66.    fns?
  67.  
  68. See the previous two FAQs on how to use "extern "C"."
  69.  
  70. ==============================================================================
  71.  
  72. Q108: How can I pass an object of a C++ class to/from a C function?
  73.  
  74. Here's an example:
  75.  
  76.         /****** C/C++ header file: Fred.h ******/
  77.         #ifdef __cplusplus    /*"__cplusplus" is #defined if/only-if compiler is C++*/
  78.           extern "C" {
  79.         #endif
  80.  
  81.         #ifdef __STDC__
  82.           extern void c_fn(struct Fred*);       /* ANSI-C prototypes */
  83.           extern struct Fred* cplusplus_callback_fn(struct Fred*);
  84.         #else
  85.           extern void c_fn();                   /* K&R style */
  86.           extern struct Fred* cplusplus_callback_fn();
  87.         #endif
  88.  
  89.         #ifdef __cplusplus
  90.           }
  91.         #endif
  92.  
  93.         #ifdef __cplusplus
  94.           class Fred {
  95.           public:
  96.             Fred();
  97.             void wilma(int);
  98.           private:
  99.             int a_;
  100.           };
  101.         #endif
  102.  
  103. "Fred.C" would be a C++ module:
  104.  
  105.         #include "Fred.h"
  106.         Fred::Fred() : a_(0) { }
  107.         void Fred::wilma(int a) : a_(a) { }
  108.  
  109.         Fred* cplusplus_callback_fn(Fred* fred)
  110.         {
  111.           fred->wilma(123);
  112.           return fred;
  113.         }
  114.  
  115. "main.C" would be a C++ module:
  116.  
  117.         #include "Fred.h"
  118.  
  119.         int main()
  120.         {
  121.           Fred fred;
  122.           c_fn(&fred);
  123.           return 0;
  124.         }
  125.  
  126. "c-fn.c" would be a C module:
  127.  
  128.         #include "Fred.h"
  129.         void c_fn(struct Fred* fred)
  130.         {
  131.           cplusplus_callback_fn(fred);
  132.         }
  133.  
  134. Passing ptrs to C++ objects to/from C fns will FAIL if you pass and get back
  135. something that isn't EXACTLY the same pointer.  For example, DON'T pass a base
  136. class ptr and receive back a derived class ptr, since your C compiler won't
  137. understand the pointer conversions necessary to handle multiple and/or virtual
  138. inheritance.
  139.  
  140. ==============================================================================
  141.  
  142. Q109: Can my C function access data in an object of a C++ class?
  143.  
  144. Sometimes.
  145.  
  146. (First read the previous FAQ on passing C++ objects to/from C functions.)
  147.  
  148. You can safely access a C++ object's data from a C function if the C++ class:
  149.  * has no virtual functions (including inherited virtual fns)
  150.  * has all its data in the same access-level section (private/protected/public)
  151.  * has no fully-contained subobjects with virtual fns
  152.  
  153. If the C++ class has any base classes at all (or if any fully contained
  154. subobjects have base classes), accessing the data will TECHNICALLY be
  155. non-portable, since class layout under inheritance isn't imposed by the
  156. language.  However in practice, all C++ compilers do it the same way: the base
  157. class object appears first (in left-to-right order in the event of multiple
  158. inheritance), and subobjects follow.
  159.  
  160. Furthermore, if the class (or any base class) contains any virtual functions,
  161. you can often (but less than always) assume a "void*" appears in the object
  162. either at the location of the first virtual function or as the first word in
  163. the object.  Again, this is not required by the language, but it is the way
  164. "everyone" does it.
  165.  
  166. If the class has any virtual base classes, it is even more complicated and less
  167. portable.  One common implementation technique is for objects to contain an
  168. object of the virtual base class (V) last (regardless of where "V" shows up as
  169. a virtual base class in the inheritance hierarchy).  The rest of the object's
  170. parts appear in the normal order.  Every derived class that has V as a virtual
  171. base class actually has a POINTER to the V part of the final object.
  172.  
  173. ==============================================================================
  174.  
  175. Q110: Why do I feel like I'm "further from the machine" in C++ as opposed to
  176.    C?
  177.  
  178. Because you are.
  179.  
  180. As an OOPL, C++ allows you to model the problem domain itself, which allows you
  181. to program in the language of the problem domain rather than in the language of
  182. the solution domain.
  183.  
  184. One of C's great strengths is the fact that it has "no hidden mechanism": what
  185. you see is what you get.  You can read a C program and "see" every clock cycle.
  186. This is not the case in C++; old line C programmers (such as many of us once
  187. were) are often ambivalent (can anyone say, "hostile") about this feature, but
  188. they soon realize that it provides a level of abstraction and economy of
  189. expression which lowers maintenance costs without destroying run-time
  190. performance.
  191.  
  192. Naturally you can write bad code in any language; C++ doesn't guarantee any
  193. particular level of quality, reusability, abstraction, or any other measure of
  194. "goodness."  C++ doesn't try to make it impossible for bad programmers to write
  195. bad programs; it enables reasonable developers to create superior software.
  196.  
  197. ==============================================================================
  198. SECTION 18: Pointers to member functions
  199. ==============================================================================
  200.  
  201. Q111: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  202.  
  203. Yep.
  204.  
  205. Consider the following function:
  206.  
  207.         int f(char a, float b);
  208.  
  209. If this is an ordinary function, its type is:    int (*)      (char,float);
  210. If this is a method of class Fred, its type is:  int (Fred::*)(char,float);
  211.  
  212. ==============================================================================
  213.  
  214. Q112: How do I pass a ptr to member fn to a signal handler, X event callback,
  215.    etc?
  216.  
  217. Don't.
  218.  
  219. Because a member function is meaningless without an object to invoke it on, you
  220. can't do this directly (if The X Windows System was rewritten in C++, it would
  221. probably pass references to OBJECTS around, not just pointers to fns; naturally
  222. the objects would embody the required function and probably a whole lot more).
  223.  
  224. As a patch for existing software, use a top-level (non-member) function as a
  225. wrapper which takes an object obtained through some other technique (held in a
  226. global, perhaps).  The top-level function would apply the desired member
  227. function against the global object.
  228.  
  229. E.g., suppose you want to call Fred::memfn() on interrupt:
  230.  
  231.         class Fred {
  232.         public:
  233.           void memfn();
  234.           static void staticmemfn();    //a static member fn can handle it
  235.           //...
  236.         };
  237.  
  238.         //wrapper fn remembers the object on which to invoke memfn in a global:
  239.         Fred* object_which_will_handle_signal;
  240.         void Fred_memfn_wrapper() { object_which_will_handle_signal->memfn(); }
  241.  
  242.         main()
  243.         {
  244.           /* signal(SIGINT, Fred::memfn); */   //Can NOT do this
  245.           signal(SIGINT, Fred_memfn_wrapper);  //Ok
  246.           signal(SIGINT, Fred::staticmemfn);   //Also Ok
  247.         }
  248.  
  249. Note: static member functions do not require an actual object to be invoked, so
  250. ptrs-to-static-member-fns are type compatible with regular ptrs-to-fns (see ARM
  251. ["Annotated Reference Manual"] p.25, 158).
  252.  
  253. ==============================================================================
  254.  
  255. Q113: Why do I keep getting compile errors (type mismatch) when I try to use a
  256.    member function as an interrupt service routine?
  257.  
  258. This is a special case of the previous two questions, therefore read the
  259. previous two answers first.
  260.  
  261. Non-static member functions have a hidden parameter that corresponds to the
  262. 'this' pointer.  The 'this' pointer points to the instance data for the
  263. object.  The interrupt hardware/firmware in the system is not capable of
  264. providing the 'this' pointer argument.  You must use "normal" functions (non
  265. class members) or static member functions as interrupt service routines.
  266.  
  267. One possible solution is to use a static member as the interrupt service
  268. routine and have that function look somewhere to find the instance/member pair
  269. that should be called on interrupt.  Thus the effect is that a normal method
  270. is invoked on an interrupt, but for technical reasons you need to call an
  271. intermediate function first.
  272.  
  273. ==============================================================================
  274.  
  275. Q114: Why am I having trouble taking the address of a C++ function?
  276.  
  277. This is a corollary to the previous FAQ.
  278.  
  279. Long answer: In C++, member fns have an implicit parameter which points to the
  280. object (the "this" ptr inside the member fn).  Normal C fns can be thought of
  281. as having a different calling convention from member fns, so the types of their
  282. ptrs (ptr-to-member-fn vs ptr-to-fn) are different and incompatible.  C++
  283. introduces a new type of ptr, called a ptr-to-member, which can be invoked only
  284. by providing an object (see ARM ["Annotated Reference Manual"] 5.5).
  285.  
  286. NOTE: do NOT attempt to "cast" a ptr-to-mem-fn into a ptr-to-fn; the result is
  287. undefined and probably disastrous.  E.g., a ptr-to- member-fn is NOT required
  288. to contain the machine addr of the appropriate fn (see ARM, 8.1.2c, p.158).  As
  289. was said in the last example, if you have a ptr to a regular C fn, use either a
  290. top-level (non-member) fn, or a "static" (class) member fn.
  291.  
  292. ==============================================================================
  293.  
  294. Q115: How do I declare an array of pointers to member functions?
  295.  
  296. Keep your sanity with "typedef".
  297.  
  298.         class Fred {
  299.         public:
  300.           int f(char x, float y);
  301.           int g(char x, float y);
  302.           int h(char x, float y);
  303.           int i(char x, float y);
  304.           //...
  305.         };
  306.  
  307.         typedef  int (Fred::*FredPtr)(char x, float y);
  308.  
  309. Here's the array of pointers to member functions:
  310.  
  311.         FredPtr a[4] = { &Fred::f, &Fred::g, &Fred::h, &Fred::i };
  312.  
  313. To call one of the member functions on object "fred":
  314.  
  315.         void userCode(Fred& fred, int methodNum, char x, float y)
  316.         {
  317.           //assume "methodNum" is between 0 and 3 inclusive
  318.           (fred.*a[methodNum])(x, y);
  319.         }
  320.  
  321. You can make the call somewhat clearer using a #define:
  322.  
  323.         #define  callMethod(object,ptrToMethod)   ((object).*(ptrToMethod))
  324.         callMethod(fred, a[methodNum]) (x, y);
  325.  
  326. ==============================================================================
  327. SECTION 19: Container classes and templates
  328. ==============================================================================
  329.  
  330. Q116: How can I insert/access/change elements from a linked
  331.    list/hashtable/etc?
  332.  
  333. I'll use an "inserting into a linked list" as a prototypical example.  It's easy
  334. to allow insertion at the head and tail of the list, but limiting ourselves to
  335. these would produce a library that is too weak (a weak library is almost worse
  336. than no library).
  337.  
  338. This answer will be a lot to swallow for novice C++'ers, so I'll give a couple
  339. of options.  The first option is easiest; the second and third are better.
  340.  
  341. [1] Empower the "List" with a "current location," and methods such as
  342. advance(), backup(), atEnd(), atBegin(), getCurrElem(), setCurrElem(Elem),
  343. insertElem(Elem), and removeElem().  Although this works in small examples, the
  344. notion of "a" current position makes it difficult to access elements at two or
  345. more positions within the List (e.g., "for all pairs x,y do the following...").
  346.  
  347. [2] Remove the above methods from the List itself, and move them to a separate
  348. class, "ListPosition."  ListPosition would act as a "current position" within a
  349. List.  This allows multiple positions within the same List.  ListPosition would
  350. be a friend of List, so List can hide its innards from the outside world (else
  351. the innards of List would have to be publicized via public methods in List).
  352. Note: ListPosition can use operator overloading for things like advance() and
  353. backup(), since operator overloading is syntactic sugar for normal methods.
  354.  
  355. [3] Consider the entire iteration as an atomic event, and create a class
  356. template to embodies this event.  This enhances performance by allowing the
  357. public access methods (which may be virtual fns) to be avoided during the inner
  358. loop.  Unfortunately you get extra object code in the application, since
  359. templates gain speed by duplicating code.  For more, see [Koenig, "Templates as
  360. interfaces," JOOP, 4, 5 (Sept 91)], and [Stroustrup, "The C++ Programming
  361. Language Second Edition," under "Comparator"].
  362.  
  363. ==============================================================================
  364.  
  365. Q117: What's the idea behind "templates"?
  366.  
  367. A template is a cookie-cutter that specifies how to cut cookies that all look
  368. pretty much the same (although the cookies can be made of various kinds of
  369. dough, they'll all have the same basic shape).  In the same way, a class
  370. template is a cookie cutter to description of how to build a family of classes
  371. that all look basically the same, and a function template describes how to
  372. build a family of similar looking functions.
  373.  
  374. Class templates are often used to build type safe containers (although this
  375. only scratches the surface for how they can be used).
  376.  
  377. ==============================================================================
  378.  
  379. Q118: What's the syntax / semantics for a "function template"?
  380.  
  381. Consider this function that swaps its two integer arguments:
  382.  
  383.         void swap(int& x, int& y)
  384.         {
  385.           int tmp = x;
  386.           x = y;
  387.           y = tmp;
  388.         }
  389.  
  390. If we also had to swap floats, longs, Strings, Sets, and FileSystems, we'd get
  391. pretty tired of coding lines that look almost identical except for the type.
  392. Mindless repetition is an ideal job for a computer, hence a function template:
  393.  
  394.         template<class T>
  395.         void swap(T& x, T& y)
  396.         {
  397.           T tmp = x;
  398.           x = y;
  399.           y = tmp;
  400.         }
  401.  
  402. Every time we used "swap()" with a given pair of types, the compiler will go to
  403. the above definition and will create yet another "template function" as an
  404. instantiation of the above.  E.g.,
  405.  
  406.         main()
  407.         {
  408.           int    i,j;  /*...*/  swap(i,j);  //instantiates a swap for "int"
  409.           float  a,b;  /*...*/  swap(a,b);  //instantiates a swap for "float"
  410.           char   c,d;  /*...*/  swap(c,d);  //instantiates a swap for "char"
  411.           String s,t;  /*...*/  swap(s,t);  //instantiates a swap for "String"
  412.         }
  413.  
  414. (note: a "template function" is the instantiation of a "function template").
  415.  
  416. ==============================================================================
  417.  
  418. Q119: What's the syntax / semantics for a "class template"?
  419.  
  420. Consider a container class of that acts like an array of integers:
  421.  
  422.         //this would go into a header file such as "Array.h"
  423.         class Array {
  424.         public:
  425.           Array(int len=10)                  : len_(len), data_(new int[len]){}
  426.          ~Array()                            { delete [] data_; }
  427.           int len() const                    { return len_;     }
  428.           const int& operator[](int i) const { data_[check(i)]; }
  429.                 int& operator[](int i)       { data_[check(i)]; }
  430.           Array(const Array&);
  431.           Array& operator= (const Array&);
  432.         private:
  433.           int  len_;
  434.           int* data_;
  435.           int  check(int i) const
  436.             { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
  437.               return i; }
  438.         };
  439.  
  440. Just as with "swap()" above, repeating the above over and over for Array of
  441. float, of char, of String, of Array-of-String, etc, will become tedious.
  442.  
  443.         //this would go into a header file such as "Array.h"
  444.         template<class T>
  445.         class Array {
  446.         public:
  447.           Array(int len=10)                : len_(len), data_(new T[len]) { }
  448.          ~Array()                          { delete [] data_; }
  449.           int len() const                  { return len_;     }
  450.           const T& operator[](int i) const { data_[check(i)]; }
  451.                 T& operator[](int i)       { data_[check(i)]; }
  452.           Array(const Array<T>&);
  453.           Array& operator= (const Array<T>&);
  454.         private:
  455.           int len_;
  456.           T*  data_;
  457.           int check(int i) const
  458.             { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
  459.               return i; }
  460.         };
  461.  
  462. Unlike template functions, template classes (instantiations of class templates)
  463. need to be explicit about the parameters over which they are instantiating:
  464.  
  465.         main()
  466.         {
  467.           Array<int>           ai;
  468.           Array<float>         af;
  469.           Array<char*>         ac;
  470.           Array<String>        as;
  471.           Array< Array<int> >  aai;
  472.         }              // ^^^-- note the space; do NOT use "Array<Array<int>>"
  473.                        //       (the compiler sees ">>" as a single token).
  474.  
  475. ==============================================================================
  476.  
  477. Q120: What is a "parameterized type"?
  478.  
  479. Another way to say, "class templates."
  480.  
  481. A parameterized type is a type that is parameterized over another type or some
  482. value.  List<int> is a type ("List") parameterized over another type ("int").
  483.  
  484. ==============================================================================
  485.  
  486. Q121: What is "genericity"?
  487.  
  488. Yet another way to say, "class templates."
  489.  
  490. Not to be confused with "generality" (which just means avoiding solutions which
  491. are overly specific), "genericity" means class templates.
  492.  
  493. ==============================================================================
  494. SECTION 20: Libraries
  495. ==============================================================================
  496.  
  497. Q122: Where can I get a copy of "STL"?
  498.  
  499. "STL" is the "Standard Templates Library".  You can get a copy from:
  500.  
  501. STL HP official site:   ftp://butler.hpl.hp.com/stl
  502. STL code alternate:     ftp://ftp.cs.rpi.edu/stl
  503. STL code + examples:    http://www.cs.rpi.edu/~musser/stl.html
  504.  
  505. STL hacks for GCC-2.6.3 are part of the GNU libg++ package 2.6.2.1 or later
  506. (and they may be in an earlier version as well).  Thanks to Mike Lindner.
  507.  
  508. ==============================================================================
  509.  
  510. Q123: Where can I ftp the code that accompanies "Numerical Recipes"?
  511.  
  512. This software is sold and there for it would be illegal to provide it on the
  513. net.  However, its only about $30.
  514.  
  515. ==============================================================================
  516.  
  517. Q124: Why is my executable so large?
  518.  
  519. Many people are surprised by how big executables are, especially if the source
  520. code is trivial.  For example, a simple "hello world" program can generate an
  521. executable that is larger than most people expect (40+K bytes).
  522.  
  523. One reason executables can be large is that portions of the C++ runtime
  524. library gets linked with your program. How much gets linked in depends on how
  525. much of it you are using, and on how the implementor split up the library into
  526. pieces.  For example, the iostream library is quite large, and consists of
  527. numerous classes and virtual functions. Using any part of it might pull in
  528. nearly all of the iostream code as a result of the interdependencies.
  529.  
  530. You might be able to make your program smaller by using a dynamically-linked
  531. version of the library instead of the static version.
  532.  
  533. You have to consult your compiler manuals or the vendor's technical support
  534. for a more detailed answer.
  535.  
  536. ==============================================================================
  537. SECTION 21: Nuances of particular implementations
  538. ==============================================================================
  539.  
  540. Q125: GNU C++ (g++) produces big executables for tiny programs; Why?
  541.  
  542. libg++ (the library used by g++) was probably compiled with debug info (-g).
  543. On some machines, recompiling libg++ without debugging can save lots of disk
  544. space (~1 Meg; the down-side: you'll be unable to trace into libg++ calls).
  545. Merely "strip"ping the executable doesn't reclaim as much as recompiling
  546. without -g followed by subsequent "strip"ping the resultant "a.out"s.
  547.  
  548. Use "size a.out" to see how big the program code and data segments really are,
  549. rather than "ls -s a.out" which includes the symbol table.
  550.  
  551. ==============================================================================
  552.  
  553. Q126: Is there a yacc-able C++ grammar?
  554.  
  555. Jim Roskind is the author of a yacc grammar for C++. It's roughly compatible
  556. with the portion of the language implemented by USL cfront 2.0 (no templates,
  557. no exceptions, no run-time-type-identification).  Jim's grammar deviates from
  558. C++ in a couple of minor-but-subtle ways.
  559.  
  560. The grammar can be accessed by anonymous ftp from the following sites:
  561.  * ics.uci.edu (128.195.1.1) in "gnu/c++grammar2.0.tar.Z".
  562.  * mach1.npac.syr.edu (128.230.7.14) in "pub/C++/c++grammar2.0.tar.Z".
  563.  
  564. ==============================================================================
  565.  
  566. Q127: What is C++ 1.2?  2.0?  2.1?  3.0?
  567.  
  568. These are not versions of the language, but rather versions of cfront, which
  569. was the original C++ translator implemented by AT&T.  It has become generally
  570. accepted to use these version numbers as if they were versions of the language
  571. itself.
  572.  
  573. *VERY* roughly speaking, these are the major features:
  574.  * 2.0 includes multiple/virtual inheritance and pure virtual functions.
  575.  * 2.1 includes semi-nested classes and "delete [] ptr_to_array."
  576.  * 3.0 includes fully-nested classes, templates and "i++" vs "++i."
  577.  * 4.0 will include exceptions.
  578.  
  579. ==============================================================================
  580.  
  581. Q128: If name mangling was standardized, could I link code compiled with
  582.    compilers from different compiler vendors?
  583.  
  584. Short answer: Probably not.
  585.  
  586. In other words, some people would like to see name mangling standards
  587. incorporated into the proposed C++ ANSI standards in an attempt to avoiding
  588. having to purchase different versions of class libraries for different
  589. compiler vendors.  However name mangling differences are one of the smallest
  590. differences between implementations, even on the same platform.  Here is a
  591. partial list of other differences:
  592.  
  593. 1) Number and type of hidden arguments to member functions.
  594.    1a) is 'this' handled specially?
  595.    1b) where is the return-by-value pointer passed?
  596. 2) Assuming a vtable is used:
  597.    2a) what is its contents and layout?
  598.    2b) where/how is the adjustment to 'this' made for multiple inheritance?
  599. 3) How are classes laid out, including:
  600.    3a) location of base classes?
  601.    3b) handling of virtual base classes?
  602.    3c) location of vtable pointers, if vtables are used?
  603. 4) Calling convention for functions, including:
  604.    4a) does caller or callee adjust the stack?
  605.    4b) where are the actual parameters placed?
  606.    4c) in what order are the actual parameters passed?
  607.    4d) how are registers saved?
  608.    4e) where does the return value go?
  609.    4f) special rules for passing or returning structs or doubles?
  610.    4g) special rules for saving registers when calling leaf functions?
  611. 5) How is the run-time-type-identification laid out?
  612. 6) How does the runtime exception handling system know which local objects
  613.    need to be destructed during an exception throw?
  614.  
  615. ==============================================================================
  616. SECTION 22: Miscellaneous technical and environmental issues
  617. ==============================================================================
  618. SUBSECTION 22A: Miscellaneous technical issues:
  619. ==============================================================================
  620.  
  621. Q129: Why are classes with static data members getting linker errors?
  622.  
  623. Static data members must be explicitly defined in exactly one module.  E.g.,
  624.  
  625.         class Fred {
  626.         public:
  627.           //...
  628.         private:
  629.           static int i_;  //declares static data member "Fred::i_"
  630.           //...
  631.         };
  632.  
  633. The linker will holler at you ("Fred::i_ is not defined") unless you define (as
  634. opposed to declare) "Fred::i_" in (exactly) one of your source files:
  635.  
  636.         int Fred::i_ = some_expression_evaluating_to_an_int;
  637. or:
  638.         int Fred::i_;
  639.  
  640. The usual place to define static data members of class "Fred" is file "Fred.C"
  641. (or "Fred.cpp", etc; whatever filename extension you use).
  642.  
  643. ==============================================================================
  644.  
  645. Q130: What's the difference between the keywords struct and class?
  646.  
  647. The members and base classes of a struct are public by default, while in class,
  648. they default to private.  Note: you should make your base classes EXPLICITLY
  649. public, private, or protected, rather than relying on the defaults.
  650.  
  651. "struct" and "class" are otherwise functionally equivalent.
  652.  
  653. ==============================================================================
  654.  
  655. Q131: Why can't I overload a function by its return type?
  656.  
  657. If you declare both "char f()" and "float f()", the compiler gives you an error
  658. message, since calling simply "f()" would be ambiguous.
  659.  
  660. ==============================================================================
  661.  
  662. Q132: What is "persistence"?  What is a "persistent object"?
  663.  
  664. A persistent object can live after the program which created it has stopped.
  665. Persistent objects can even outlive different versions of the creating program,
  666. can outlive the disk system, the operating system, or even the hardware on
  667. which the OS was running when they were created.
  668.  
  669. The challenge with persistent objects is to effectively store their method code
  670. out on secondary storage along with their data bits (and the data bits and
  671. method code of all member objects, and of all their member objects and base
  672. classes, etc).  This is non-trivial when you have to do it yourself.  In C++,
  673. you have to do it yourself.  C++/OO databases can help hide the mechanism for
  674. all this.
  675.  
  676. ==============================================================================
  677.  
  678. Q133: Why is floating point so inaccurate?  Why doesn't this print 0.43?
  679.  
  680.         #include<iostream.h>
  681.  
  682.         main()
  683.         {
  684.           float a = 1000.43;
  685.           float a = 1000.0;
  686.           cout << a - b << '\n';
  687.         }
  688.  
  689. (note, on one C++ implementation, this prints 0.429993)
  690.  
  691. Disclaimer: Frustration with rounding/truncation/approximation isn't really a
  692. C++ issue.  It's a computer science issue.  However, people keep asking about
  693. it on comp.lang.c++, so here's a nominal answer.
  694.  
  695. Answer: Floating point is an approximation.  The IEEE standard for 32 bit
  696. float supports 1 bit of sign, 8 bits of exponent, and 23 bits of mantissa.
  697. Since a normalized binary-point mantissa always has the form 1.xxxxx... the
  698. leading 1 is dropped and you get effectively 24 bits of mantissa.  The number
  699. 1000.43 (and many, many others) is not exactly representable in float or
  700. double format.  1000.43 is actually represented as the following bitpattern
  701. (the 's' shows the position of the sign bit, the 'e's show the positions of
  702. the exponent bits, and the 'm's show the positions of the mantissa bits):
  703.  
  704.     seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm
  705.     01000100011110100001101110000101
  706.  
  707. The shifted mantissa is 1111101000.01101110000101 or 1000 + 7045/16384.  The
  708. fractional part is 0.429992675781.  With 24 bits of mantissa you only get
  709. about 1 part in 16M of precision for float.  The 'double' type provides more
  710. precision (53 bits of mantissa).
  711.  
  712. ==============================================================================
  713. SUBSECTION 22B: Miscellaneous environmental issues:
  714. ==============================================================================
  715.  
  716. Q134: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  717.  
  718. Yes, here are two:
  719.  
  720. \def\CC{C\raise.22ex\hbox{{\footnotesize +}}\raise.22ex\hbox{\footnotesize +}}
  721.  
  722. \def\CC{{C\hspace{-.05em}\raisebox{.4ex}{\tiny\bf ++}}}
  723.  
  724. ==============================================================================
  725.  
  726. Q135: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  727.  
  728. Here are a few ftp locations:
  729.  
  730. Host aix370.rrz.uni-koeln.de   (134.95.80.1) Last updated 15:41 26 Apr 1991
  731.     Location: /tex
  732.       FILE      rw-rw-r--     59855  May  5  1990   C++2LaTeX-1.1.tar.Z
  733. Host utsun.s.u-tokyo.ac.jp   (133.11.11.11) Last updated 05:06 20 Apr 1991
  734.     Location: /TeX/macros
  735.       FILE      rw-r--r--     59855  Mar  4 08:16   C++2LaTeX-1.1.tar.Z
  736. Host nuri.inria.fr   (128.93.1.26) Last updated 05:23  9 Apr 1991
  737.     Location: /TeX/tools
  738.       FILE      rw-rw-r--     59855  Oct 23 16:05   C++2LaTeX-1.1.tar.Z
  739. Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
  740.     Location: /TeX
  741.       FILE      rw-r--r--     59855  Apr 25  1990   C++2LaTeX-1.1.tar.Z
  742. Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
  743.     Location: /TeX
  744.       FILE      rw-r--r--     51737  Apr 30  1990
  745.       C++2LaTeX-1.1-PL1.tar.Z
  746. Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07 18 Apr 1991
  747.     Location: /pub/textproc/TeX
  748.       FILE      rw-r--r--     72957  Oct 25 13:51  C++2LaTeX-1.1-PL4.tar.Z
  749. Host wuarchive.wustl.edu   (128.252.135.4) Last updated 23:25 30 Apr 1991
  750.     Location: /packages/tex/tex/192.35.229.9/textproc/TeX
  751.       FILE      rw-rw-r--     49104  Apr 10  1990   C++2LaTeX-PL2.tar.Z
  752.       FILE      rw-rw-r--     25835  Apr 10  1990   C++2LaTeX.tar.Z
  753. Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07 18 Apr 1991
  754.     Location: /pub/textproc/TeX
  755.       FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
  756.     Location: /pub
  757.       FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
  758. Host sol.cs.ruu.nl   (131.211.80.5) Last updated 05:10 15 Apr 1991
  759.     Location: /TEX/TOOLS
  760.       FILE      rw-r--r--     74015  Apr  4 21:02x   C++2LaTeX-1.1-PL5.tar.Z
  761. Host tupac-amaru.informatik.rwth-aachen.de (192.35.229.9) Last updated 05:07 18 Apr 1991
  762.     Location: /pub/textproc/TeX
  763.       FILE      rw-r--r--      4792  Sep 11  1990 C++2LaTeX-1.1-patch#1
  764.       FILE      rw-r--r--      2385  Sep 11  1990 C++2LaTeX-1.1-patch#2
  765.       FILE      rw-r--r--      5069  Sep 11  1990 C++2LaTeX-1.1-patch#3
  766.       FILE      rw-r--r--      1587  Oct 25 13:58 C++2LaTeX-1.1-patch#4
  767.       FILE      rw-r--r--      8869  Mar 22 16:23 C++2LaTeX-1.1-patch#5
  768.       FILE      rw-r--r--      1869  Mar 22 16:23 C++2LaTeX.README
  769. Host rusmv1.rus.uni-stuttgart.de   (129.69.1.12) Last updated 05:13 13 Apr 1991
  770.     Location: /soft/tex/utilities
  771.       FILE      rw-rw-r--    163840  Jul 16  1990   C++2LaTeX-1.1.tar
  772.  
  773. ==============================================================================
  774.  
  775. Q136: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  776.  
  777. "tgrind" reads a C++ source file, and spits out something that looks pretty on
  778. most Unix printers.  It usually comes with the public distribution of TeX and
  779. LaTeX; look in the directory: "...tex82/contrib/van/tgrind".  A more up-to-date
  780. version of tgrind by Jerry Leichter can be found on: venus.ycc.yale.edu in
  781. [.TGRIND].
  782.  
  783. ==============================================================================
  784.  
  785. Q137: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  786.  
  787. Yes, there is a C++-mode for GNU emacs.
  788.  
  789. The latest and greatest version of C++-mode (and c-mode) is implemented in the
  790. file cc-mode.el.  It is an extension of Detlef & Clamen's version.
  791. A version is included with emacs.  Newer version are availiable from
  792. the elisp archives.
  793.  
  794. ==============================================================================
  795.  
  796. Q138: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  797.  
  798. See one of the following:
  799.  * comp.os.msdos.programmer
  800.  * comp.windows.ms.programmer
  801.  * comp.unix.programmer
  802.  
  803. [If anyone has an email address for a BC++, VC++, or Semantic C++ bug list
  804. and/or discussion mailing list, please let me know how to subscribe, and I'll
  805. mention it here].
  806.  
  807. ==============================================================================
  808.  
  809. Q139: Why does my DOS C++ program says "Sorry: floating point code not
  810.    linked"?
  811.  
  812. The compiler attempts to save space in the executable by not including the
  813. float-to-string format conversion routines unless they are necessary, but
  814. sometimes it guesses wrong, and gives you the above error message.  You can fix
  815. this by (1) using <iostream.h> instead of <stdio.h>, or (2) by including the
  816. following function somewhere in your compilation (but don't call it!):
  817.  
  818.         static void dummyfloat(float *x) { float y; dummyfloat(&y); }
  819.  
  820. See FAQ on stream I/O for more reasons to use <iostream.h> vs <stdio.h>.
  821.  
  822. ==============================================================================
  823.  
  824. Q140: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  825.  
  826. If you're using BC++ for a Windows app, and it works ok as long as you have the
  827. BC45 IDE running, but when the BC45 IDE is shut down you get an exception
  828. during the creation of a window, then add the following line of code to the
  829. InitMainWindow() method of your application ("YourApp::InitMainWindow()"):
  830.  
  831.         EnableBWCC(TRUE);
  832.  
  833. ==============================================================================
  834.  
  835. --
  836. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  837. Technology consulting services
  838. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  839.  
  840.  
  841.